package com.ethanzzh.ethanzzh_xdclass.controller;

import com.ethanzzh.ethanzzh_xdclass.dto.VideoOrderDTO;
import com.ethanzzh.ethanzzh_xdclass.service.VideoOrderService;
import com.ethanzzh.ethanzzh_xdclass.utils.IpUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/api/v1/order")
//@RequestMapping("/api/v1/order")

public class OrderController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Logger dataLogger = LoggerFactory.getLogger("dataLogger");


    @Autowired
    private VideoOrderService videoOrderService;

    @GetMapping("/add")
    public void saveOrder(@RequestParam(value = "video_id") int videoId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String ip = IpUtils.getIpAddr(request);
        int userId = (Integer) request.getAttribute("user_id");
//        String ip = "192.167.188.122";
//        int userId = 1;

        VideoOrderDTO videoOrderDTO = new VideoOrderDTO();
        videoOrderDTO.setUserId(userId);
        videoOrderDTO.setIp(ip);
        videoOrderDTO.setVideoId(videoId);
        //下单返回code_url
        String codeUrl = videoOrderService.save(videoOrderDTO);
        if (codeUrl == null) {
            throw new NullPointerException();
        }

        try {
            //生成二维码
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //设置纠错等级
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            //编码类型
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            //构成图片对象（内容，格式，宽，高，配置）
            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 400, 400, hints);
            //拿到输出流
            OutputStream out = response.getOutputStream();

            MatrixToImageWriter.writeToStream(bitMatrix,"png",out);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
